package com.thinksmart.qfilemanager;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.qnap.qdk.qtshttp.QtsHttpCancelController;
import com.qnap.qdk.qtshttp.filestation.QtsHttpFileEntry;
import com.thinksmart.qfilemanager.adapter.FilelistItemAdapter;
import com.thinksmart.qfilemanager.widget.listItem;

import java.util.ArrayList;

public class fileListActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private ListView lvMenu, lvFileList;
    private DrawerLayout dlLeft;
    private String[] lvs;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout.DrawerListener dlListener;
    private ArrayAdapter adpMenu;

    private String mParentPath;
    private ArrayList<QtsHttpFileEntry> mQFileEntryList;
    private String mCurrentPath; //Current file/folder path

    private static final int MSG_UPDATELIST = 0;
    private static final int MSG_UPDATEPROGRESS = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_list);

        Intent intent = getIntent();
        mParentPath = intent.getStringExtra("relativePath");
        mCurrentPath = mParentPath;

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        dlLeft = (DrawerLayout) findViewById(R.id.dl_left);
        lvMenu = (ListView) findViewById(R.id.lv_Menu);
        lvFileList = (ListView) findViewById(R.id.lv_FileList);
        lvs = new String[]{getResources().getString(R.string.background),
                getResources().getString(R.string.setting),
                getResources().getString(R.string.about),
                getResources().getString(R.string.logout)};

        toolbar.setTitle(getResources().getString(getApplicationInfo().labelRes));
        toolbar.setTitleTextColor(Color.parseColor("#ffffff"));
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, dlLeft, toolbar, 0, 0);
        mDrawerToggle.syncState();
        dlListener = new MyDrawerListener();
        dlLeft.addDrawerListener(dlListener);

        adpMenu = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lvs);
        lvMenu.setAdapter(adpMenu);
        lvMenu.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String str = (String)parent.getItemAtPosition(position);
                if (str.equals(getResources().getString(R.string.logout))) {
                    finish();
                }
            }
        });

        lvFileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                QtsHttpFileEntry entry = null;
                if (mQFileEntryList == null) return;
                if (mQFileEntryList != null && mQFileEntryList.isEmpty()) return;

                entry = mQFileEntryList.get(position);
                String nextPath;

                if (entry.isDir()) {
                    if (entry.getFilePath().equals("/")) {
                        nextPath = entry.getFilePath() + entry.getFileName();
                    }
                    else {
                        nextPath = entry.getFilePath() + "/" + entry.getFileName();
                    }
                    getFileEntryList(nextPath);
                }
            }
        });

        getFileEntryList(mParentPath);
    }

    private class MyDrawerListener implements DrawerLayout.DrawerListener {
        @Override
        public void onDrawerOpened(View drawerView) {
            mDrawerToggle.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            mDrawerToggle.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            mDrawerToggle.onDrawerStateChanged(newState);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATELIST:
                    ArrayList<listItem> allFileNameList = msg.getData().getParcelableArrayList("fileNameList");
                    FilelistItemAdapter adapter = new FilelistItemAdapter(allFileNameList, fileListActivity.this);
                    lvFileList.setAdapter(adapter);
                    lvFileList.invalidate();
                    break;
            }
        }
    };

    private void getFileEntryList(final String path) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                mQFileEntryList = null;
                QtsHttpCancelController cancel = new QtsHttpCancelController();

                try {
                    if (path.equals("/")) {
                        mQFileEntryList = loginActivity.mFileStation.getShareFolderList(cancel);
                    }else {
                        mQFileEntryList = loginActivity.mFileStation.getFileList(path, 0, 50, cancel);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (mQFileEntryList == null) return;
                    if (mQFileEntryList != null && mQFileEntryList.isEmpty()) return;
                    mCurrentPath = path;
                    ArrayList<listItem> allFileNameList = new ArrayList<listItem>();

                    for (QtsHttpFileEntry entry:mQFileEntryList) {
                        listItem item = new listItem();
                        if (entry.isDir()) {
                            item.setDir(true);
                            item.setIcon(R.mipmap.ic_folder);
                        }else {
                            item.setDir(false);
                            item.setIcon(R.mipmap.ic_file);
                        }
                        item.setText(entry.getFileName());
                        allFileNameList.add(item);
                    }

                    Message msg = new Message();
                    Bundle data = msg.getData();
                    data.putParcelableArrayList("fileNameList", allFileNameList);
                    msg.setData(data);
                    msg.what = MSG_UPDATELIST;
                    mHandler.sendMessage(msg);
                }
            }
        };
        thread.start();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mCurrentPath != null) {
                getFileEntryList(getParentPath());
            }
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private String getParentPath() {
        String parentPath = null;

        //Check current path
        if (mQFileEntryList != null && !mQFileEntryList.isEmpty()) {
            if (!mCurrentPath.equals(mQFileEntryList.get(0).getFilePath())) {
                mCurrentPath = mQFileEntryList.get(0).getFilePath();
            }
        }

        //Get parent path
        if (mCurrentPath != null) {
            int index = mCurrentPath.lastIndexOf('/');
            if (index == 0)
                parentPath = "/";
            else
                parentPath = mCurrentPath.substring(0, index);
        }

        return parentPath;
    }
}
